// pages/person/person.js
const app = getApp(); var sign_flag;
var canUp =true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popup: false, //是否赞一键获取手机号码
    phone: '', //手机号码
    userInfo: '',
    user: [],
    // 签到
    is_login: false,
    integral_conf:{},//积分赠送
    sign_day: {},
    signstate: '',
    toDay:'',//今天

    is_load:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    //wx.setStorageSync('token', '');  清空token 
  },
  bindgetuserinfofun: function (e) {
    var that = this;
    if (e.detail.errMsg == 'getUserInfo:fail:cancel to confirm login' || e.detail.errMsg == 'getUserInfo:fail auth deny') {
      app.showToast("取消登录", "none", 2000, function () {});
    } else {
      that.setData({
        userInfo: e.detail.userInfo
      })
      console.log('获取到的授权信息', that.data.userInfo);
      that.editUserInfo(that.data.userInfo); //更新一次用户信息
      wx.setStorageSync('avatarUrl', e.detail.userInfo.avatarUrl); //缓存头像
      wx.setStorageSync('nickName', e.detail.userInfo.nickName); //缓存名称
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    canUp = true;
    var is_login = wx.getStorageSync('is_login') == true ? true : false;
    that.setData({
      is_login: is_login
    })
    if (!is_login) {
      //没登录不做处理
    } else {
      this.getsign();//获取签到配置
      this.signDay();//签到天数
      this.getUser();
    }
    
    //获取用户信息
  },
  // 我的优惠券
  checkMyCoupons: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../receivedcoupons/receivedcoupons',
      })
    }
  },
  //关于我们 
  aboutWe: function () {
    wx.navigateTo({
      url: '../aboutWe/aboutWe',
    })
  },
  //更新记录
  version: function () {
    wx.navigateTo({
      url: '../version/list/list',
    })
  },
  //跳转
  invitation: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      // wx.navigateTo({ 
      //   url: '../invitation/invitation',
      // })
    }
  },
  //跳转我的积分
  myIntegral: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../myIntegral/myIntegral',
      })
    }
  },
  //跳转我的订单
  myOrder: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../myOrderList/myOrderList?have=2',
      })
    }
  },
  //取消一键登录  返回首页
  abolish() {
    var that = this;
    that.setData({
      popup: false
    })
    wx.redirectTo({
      url: '../home/home',
    })
  },

  //敬请期待
  myPurifier: function () {
    wx.showModal({
      title: '该功能即将上线敬请期待',
      showCancel: false,
      success: function (res) {

      }
    })
  },
  //获取用户手机号码
  getPhoneNumber: function (e) {
    var iv = e.detail.iv,
      encryptedData = e.detail.encryptedData,
      that = this;
    if (e.detail.errMsg == 'getPhoneNumber:fail:cancel to confirm login' || e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      that.setData({
        popup: false
      })
      wx.navigateTo({
        url: '../login/login',
      })
    } else {
      that.getAjaxPhone(iv, encryptedData); //后台解析手机信息
    }
  },
  //后台解析手机号码
  getAjaxPhone(iv, encryptedData) {
    var that = this;
    var session_key = wx.getStorageSync('session_key');
    app.ajax({
      url: "User/Wx/aesPhoneDecrypt",
      data: {
        key: session_key,
        iv: iv,
        data: encryptedData
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            popup: false
          })
          wx.setStorageSync('phone', res.data.data.phoneNumber);
          wx.setStorageSync('phone', res.data.data.phoneNumber);
          wx.setStorageSync('token', ''); //清空本地token
          app.getToken(); //重新获取token 保存手机号码重新登录
        } else {
          app.showToast('用户信息解析失败请重新授权', "none", 2000, function () {});
          return false;
        }
      }
    })
  },
  //获取用户信息
  getUser() {
    var that = this;
    app.ajax({
      url: "User/User/getUser",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            user: res.data.data,
            phone: res.data.data.phone,
            // nickName: res.data.data.wx_nickname
          })
          wx.setStorageSync('user_id', res.data.data.user_id)
          // if (res.data.data.wx_nickname == "") {
          //   app.getToken();
          // }
          var phone = res.data.data.phone;
          wx.setStorageSync('phone', phone);
          if (phone == '') {
            that.setData({
              popup: true
            })
            return;
          }

        } else {
          wx.setStorageSync('token', '');
          // app.getToken(); 
          that.setData({
            popup: true
          })
        }
        that.setData({
          is_load: true
        })
      }
    })
  },

  navBuyRecord() {
    wx.navigateTo({
      url: '../sellCard/buy-record/buy-record',
    })
  },

  // 首页
  goHome: function () {
    wx.redirectTo({
      url: '../home/home',
    })
  },
  //扫码
  scan: function () {
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      // 只允许从相机扫码
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          var newsp = res.result.split("=");
          if (newsp.length == 2 && newsp[2] != '') {
            wx.navigateTo({
              url: '../gettingWater/gettingWater?equipment_sn=' + newsp[1] + '&have=' + 1,
            })
          } else {
            app.showToast('扫码失败请重试', "none", 2000, function () {});
          }
        }
      })
    }
  },
  //需要前去登陆
  goSetting(e) {
    var that = this;
    var phone = that.data.phone;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../setting/setting?phone=' + phone,
      })
    }
  },
  //需要前去登陆
  gologin() {
    wx.showModal({
      title: '该功能需要登录之后才能体验',
      content: '是否前去登录?',
      confirmColor: '#1CBFFF',	
      cancelColor:'#C4C4C4',
      success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../loginChoose/loginChoose',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //我的家用设备
  toMyHomeDevice() {
    var path = 'pages/home/home';
    var appId = app.globalData.cloud_user_appid;
    var extraData = {
      'from': 'water'
    };
    var envVersion = 'trial'; //trial体验版release正式版
    app.navigateToMiniProgram(appId, path, extraData, envVersion);
  },
  //修改用户信息
  editUserInfo(userMsg) {
    var that = this;
    app.ajax({
      url: "User/User/editUserInfo",
      data: {
        avatar_img: userMsg.avatarUrl,
        username: userMsg.nickName,
      },
      success: function (res) {
        if (res.data.code == 1000) {

        } else {

        }
        wx.navigateTo({
          url: '../invitation/invitation',
        })
      }
    })
  },
  //加载成功
  bindload(e) {
    console.log("加载成功", e)
  },
  //加载失败
  binderror(e) {
    console.log('加载失败', e)
  },
  // 跳转积分规则
  ruleBtn: function () {
    wx.navigateTo({
      url: '../integralRule/integralRule?type=1',
    })
  },
  //任务
  task(){
    var that = this;
    var is_login = wx.getStorageSync('is_login');
    if (!is_login) {
      that.gologin();
      return
    } else {
      wx.navigateTo({
        url: '../task/task',
      })
    }
    
  },
  
  //获取签到配置
  getsign: function () {
    var that = this;2
    app.ajax({
      url: 'User/Sign/integral_conf',
      data: {},
      method: 'POST',
      success: function (res) {
        if (res.data.code == 1000) {
          var integral_conf=res.data.data;
          integral_conf.seven = parseInt(integral_conf.seven) + parseInt(integral_conf.sign);
          integral_conf.three = parseInt(integral_conf.three) + parseInt(integral_conf.sign);
          that.setData({
            integral_conf
          })
        }
      }
    })
  },
  //获取签到天数
  signDay: function () {
    var that = this;
    app.ajax({
      url: 'User/Sign/sign_day',
      data: {},
      method: 'POST',
      success: function (res) {
        if (res.data.code == 1000) {
          if (res.data.data.is_sign == 1) {
            sign_flag = false
          } else {
            sign_flag = true
          }
          var sign_day = res.data.data
          // sign_day.is_sign=0;//模拟数据
          // sign_day.cycle_day=3;//模拟数据
          // console.log('签到数据', sign_day)
          that.setData({
            sign_day,
            signstate: res.data.data.is_sign,//0今天未签到 1已签到 
          })
        }
      }
    })
  },

  signOver() { this.data.signstate==1?app.showToast('今日已签到,明天再来吧'):''},
  //签到
  signfun: function (e) {
    var current = e.currentTarget.dataset.current;
    var that = this;
    if (!sign_flag) {
      app.showToast('今日已签到');
      return false;
    }
    app.ajax({
      url: 'User/Sign/sign',
      data: {},
      method: 'POST',
      success: function (res) {  
        if (res.data.code == 1000) {
          var integral_conf = that.data.integral_conf;
          integral_conf.sign_data.forEach((item,index)=>{
            if (item.current_cycle_day == current){
              integral_conf.sign_data[index].is_sign = true;
            }
          })
          // integral_conf.sign_data[index].is_sign=true;
          // console.log('>>>>>', integral_conf)
          that.setData({
            signstate: 1,
            integral_conf
          });
          sign_flag = false
        } else {
          // sign_flag = false
        }
        app.showToast(res.data.message);
        that.signDay();//获取签到状态
        that.getUser();//获取用户信息
      }
    })
  },


  //解析用户信息
  bindgetuserinfofun: function (e) {
    var that = this;
    var { id, k } = e.currentTarget.dataset;
    if (e.detail.errMsg == 'getUserInfo:fail:cancel to confirm login' || e.detail.errMsg == 'getUserInfo:fail auth deny') {
      app.showToast("已取消授权", "none", 2000, function () { });
    } else {
      that.editUserInfo(e.detail.userInfo); //更新一次用户信息
      //that.getIntegral(id, k, e.detail.userInfo);
      wx.setStorageSync('avatarUrl', e.detail.userInfo.avatarUrl); //缓存头像
      wx.setStorageSync('nickName', e.detail.userInfo.nickName); //缓存名称
    }
  },
  //兑换积分
  getIntegral(id, k, userMsg) {
    var that = this;
    if (!canUp) { return false };
    canUp = false;
    app.ajax({
      url: "User/Task/receive",
      data: {
        id: id,
        avatar_img: userMsg.avatarUrl,
        username: userMsg.nickName,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.getUser();
          var tasksList = that.data.tasksList;
          tasksList[k].is_receive = 1;
          that.setData({
            tasksList
          })
        }
        //兑换积分加一个开关;//开关生效时间2秒
        setTimeout(() => {
          canUp = true;
        }, 2000);
        app.showToast(res.data.message, "none", 2000, function () { });
      }
    })
  },

  //跳转身申请合伙人
  partnerApply(){
    wx.navigateTo({
      url: '../partnerApply/partnerApply',
    })
  }
})